/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.core.validation.builtinimpls.adaptors;

import com.inspur.edp.bef.api.action.validation.IValidationContext;
import com.inspur.edp.bef.core.action.base.ActionUtil;
import com.inspur.edp.cef.api.validation.ICefValidationContext;
import com.inspur.edp.cef.core.action.CompReflector;
import com.inspur.edp.cef.core.validation.builtinimpls.valadaptors.BaseValAdaptor;
import com.inspur.edp.cef.entity.changeset.ChangeType;
import com.inspur.edp.cef.entity.changeset.ChildElementsTuple;
import com.inspur.edp.cef.entity.changeset.IChangeDetail;
import com.inspur.edp.cef.entity.changeset.Util;
import java.util.List;

public class BefBaseValAdaptor extends BaseValAdaptor {

  private final List<ChangeType> changeTypes;
  private final List<String> elements;
  private final List<ChildElementsTuple> childElements;
  //TODO:改改基类
  private final Class type;

  public BefBaseValAdaptor(Class type, List<ChangeType> changeTypes) {
    this(type, changeTypes, null, null);
  }

  public BefBaseValAdaptor(Class type, List<ChangeType> changeTypes, List<String> elements) {
    this(type, changeTypes, elements, null);
  }

  public BefBaseValAdaptor(Class type, List<ChangeType> changeTypes, List<String> elements,
      List<ChildElementsTuple> childElements) {
    super(type, new CompReflector(type, IValidationContext.class, IChangeDetail.class));
    this.type = type;
    this.changeTypes = changeTypes;
    this.elements = elements;
    this.childElements = childElements;
  }

  @Override
  public boolean canExecute(IChangeDetail iChangeDetail) {
    if (changeTypes != null && !changeTypes.contains(iChangeDetail.getChangeType())) {
      return false;
    }
    if (elements != null && Util.containsAny(iChangeDetail, elements)) {
      return true;
    }
    if (childElements != null && childElements.stream().anyMatch(childElement -> Util
        .containsChildAny(iChangeDetail, childElement.getItem1(), childElement.getItem2()))) {
      return true;
    }
    return elements == null && childElements == null;
  }

  @Override
  public void execute(ICefValidationContext ctx, IChangeDetail change) {
    String id = ActionUtil.getBizContextId();
    super.execute(ctx, change);
    ActionUtil.checkSessionChanged(id, null, ActionUtil.CATEGORY_VALIDATION, type);
  }
}
